package org.grow.commodity.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.grow.commodity.dao.DistributorDao;
import org.grow.commodity.entity.*;
import org.grow.commodity.exception.CommodityException;
import org.grow.commodity.util.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author: xwg
 * @CreateDate: 21-8-9
 */
@RestController
@RequestMapping("/commodity/distributor")
public class DistributorController {
    @Resource
    private ThreadLocal<CodeGenerator> codeGeneratorTemplate;
    @Resource
    private DistributorDao distributorDao;

    @PostMapping("/")
    public String insert(@RequestBody Distributor distributor) {
//        第一 前端传过来的数据格式校验

        String phoneNumber = distributor.getPhoneNumber();
        boolean matches = Pattern.matches("^1[3|4|5|7|8][0-9]{9}$", phoneNumber);
        if (!matches) throw new CommodityException("手机号格式不正确", 820);
//        第二 后端数据生成填充
//        初始化信用等级5级 再可以继续增 可以降低
        distributor.setCreditLevel(0);
        distributor.setDistributorCode(
                codeGeneratorTemplate.get().nextCode(
                        CommodityConst.Distributor));
        distributor.setDistributorId(-1);
        distributor.setIsDeleted(false);
        int insert = distributorDao.insert(distributor);
        return insert == 1 ? distributor.getDistributorCode() : null;
    }

    @PostMapping("/query")
    public PagedResults<Distributor> query(@RequestBody DistributorSearchForm distributorSearchForm) {
        Integer pageNum = distributorSearchForm.getPageNum();
        Integer pageSize = distributorSearchForm.getPageSize();
        DistributorQueryCondition qc = distributorSearchForm.getQueryCondition();
        IPage<Distributor> distributorIPage = distributorDao.dynamicQuery(new Page<Distributor>(pageNum, pageSize), qc);
        PagedResults<Distributor> pagedResults = new PagedResults<>();
        pagedResults.setResults(distributorIPage.getRecords());
        pagedResults.setTotal(distributorIPage.getTotal());
        return pagedResults;
    }

    @GetMapping("/find")
    public List<Distributor> find(@RequestParam("nameOrCode") String nameOrCode){

        return  distributorDao.findByCodeOrName(nameOrCode);
    }
}
